package com.guanyu.u2cache.confinuelife;

import lombok.Getter;
import lombok.NoArgsConstructor;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author zhouyunjian
 * @date 2023/11/20 15:05
 * 延时队列
 **/
@Getter
@NoArgsConstructor
public class DelayedTask implements Delayed {
    private long delay;
    private long expire;
    private CachedInvocation cachedInvocation;

    public DelayedTask(CachedInvocation cachedInvocation) {
        this.cachedInvocation = cachedInvocation;
        this.delay = cachedInvocation.getMetaData().getDelayTime() * 1000;
        this.expire = System.currentTimeMillis() + this.delay;
    }

    /**
     * 获取延时时间
     *
     * @param unit
     * @return
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.expire - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    /**
     * 比较延时队列顺序
     *
     * @param o
     * @return
     */
    @Override
    public int compareTo(Delayed o) {
        return (int) (this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
    }
}
